package com.hyq.learn.web.listenen;

import com.hyq.learn.common.util.HostNameUtil;
import com.hyq.learn.web.env.LearnEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author heyuqin
 * @date 2024/5/27 17:18
 */
public class ApplicationStartListener implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationStartListener.class);

    private final LearnEnvironment learnEnvironment;

    public ApplicationStartListener(LearnEnvironment learnEnvironment) {
        this.learnEnvironment = learnEnvironment;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String port = environment.getProperty("server.port");
        String applicationName = environment.getProperty("spring.application.name");
        String ipAddress = HostNameUtil.localIpAddress();
        List<String> profiles = Arrays.stream(environment.getActiveProfiles()).collect(Collectors.toList());
        LOGGER.info("\n----------------------------------------\n\t" +
                "Application {} is running!\n\t" +
                "Local: http://127.0.0.1:{}\n\t" +
                "ip: http://{}:{}\n\t" +
                "profiles: {}\n" +
                "----------------------------------------\n", applicationName, port, ipAddress, port, profiles);
    }
}
